<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="收银员编码" prop="cashierCode">
        <el-input
          v-model="queryParams.cashierCode"
          placeholder="请输入收银员编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收银员姓名" prop="cashierName">
        <el-input
          v-model="queryParams.cashierName"
          placeholder="请输入收银员姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pos:cashier:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pos:cashier:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pos:cashier:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pos:cashier:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cashierList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="收银员ID" align="center" prop="cashierId" />
      <el-table-column label="收银员编码" align="center" prop="cashierCode" />
      <el-table-column label="收银员姓名" align="center" prop="cashierName" />
      <el-table-column label="手机号码" align="center" prop="phone" />
      <el-table-column label="管理柜组" align="center" prop="groupNames" width="200">
        <template slot-scope="scope">
          <span :title="scope.row.groupNames">{{ scope.row.groupNames || '未设置' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="可用设备" align="center" prop="deviceNames" width="200">
        <template slot-scope="scope">
          <span :title="scope.row.deviceNames">{{ scope.row.deviceNames || '未设置' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pos:cashier:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-key"
            @click="handleChangePassword(scope.row)"
            v-hasPermi="['pos:cashier:edit']"
          >修改密码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-grid"
            @click="handleSetGroups(scope.row)"
            v-hasPermi="['pos:cashier:edit']"
          >设置柜组</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-monitor"
            @click="handleSetDevices(scope.row)"
            v-hasPermi="['pos:cashier:edit']"
          >设置设备</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pos:cashier:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改收银员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="收银员编码" prop="cashierCode">
          <el-input v-model="form.cashierCode" placeholder="请输入收银员编码" />
        </el-form-item>
        <el-form-item label="收银员姓名" prop="cashierName">
          <el-input v-model="form.cashierName" placeholder="请输入收银员姓名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="form.cashierId == null">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" :visible.sync="passwordOpen" width="500px" append-to-body>
      <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px">
        <el-form-item label="收银员编码" prop="cashierCode">
          <el-input v-model="passwordForm.cashierCode" :disabled="true" />
        </el-form-item>
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码（6-20位）" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPasswordForm">确 定</el-button>
        <el-button @click="cancelPassword">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 柜组维护对话框 -->
    <el-dialog title="设置管理柜组" :visible.sync="groupsOpen" width="600px" append-to-body>
      <div class="dialog-header">
        <span>收银员：{{ currentCashier.cashierName }} ({{ currentCashier.cashierCode }})</span>
      </div>
      <el-divider></el-divider>
      <el-form label-width="120px">
        <el-form-item label="可选柜组：">
          <el-checkbox-group v-model="selectedGroups" @change="handleGroupChange">
            <el-checkbox 
              v-for="group in availableGroups" 
              :key="group.groupId" 
              :label="group.groupId"
              style="display: block; margin-bottom: 10px;"
            >
              {{ group.groupName }} ({{ group.groupCode }})
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="已选柜组：">
          <el-tag 
            v-for="group in selectedGroupNames" 
            :key="group.groupId"
            closable
            @close="removeGroup(group.groupId)"
            style="margin-right: 10px; margin-bottom: 5px;"
          >
            {{ group.groupName }}
          </el-tag>
          <span v-if="selectedGroupNames.length === 0" style="color: #999;">未选择任何柜组</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGroups">确 定</el-button>
        <el-button @click="cancelGroups">取 消</el-button>
      </div>
    </el-dialog>

    <!-- POS设备维护对话框 -->
    <el-dialog title="设置可用设备" :visible.sync="devicesOpen" width="600px" append-to-body>
      <div class="dialog-header">
        <span>收银员：{{ currentCashier.cashierName }} ({{ currentCashier.cashierCode }})</span>
      </div>
      <el-divider></el-divider>
      <el-form label-width="120px">
        <el-form-item label="可选设备：">
          <el-checkbox-group v-model="selectedDevices" @change="handleDeviceChange">
            <el-checkbox 
              v-for="device in availableDevices" 
              :key="device.deviceId" 
              :label="device.deviceId"
              style="display: block; margin-bottom: 10px;"
            >
              {{ device.deviceName }} ({{ device.deviceCode }})
              <el-tag size="mini" :type="device.status === '0' ? 'success' : 'danger'" style="margin-left: 10px;">
                {{ device.status === '0' ? '正常' : '停用' }}
              </el-tag>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="已选设备：">
          <el-tag 
            v-for="device in selectedDeviceNames" 
            :key="device.deviceId"
            closable
            @close="removeDevice(device.deviceId)"
            style="margin-right: 10px; margin-bottom: 5px;"
          >
            {{ device.deviceName }}
          </el-tag>
          <span v-if="selectedDeviceNames.length === 0" style="color: #999;">未选择任何设备</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDevices">确 定</el-button>
        <el-button @click="cancelDevices">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCashier, getCashier, delCashier, addCashier, updateCashier, changePassword, getCashierGroups, getCashierDevices, setCashierGroups, setCashierDevices } from "@/api/pos/cashier";
import { listGroup } from "@/api/pos/group";
import { listDevice } from "@/api/pos/device";

export default {
  name: "Cashier",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 收银员表格数据
      cashierList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示密码修改弹出层
      passwordOpen: false,
      // 是否显示柜组维护弹出层
      groupsOpen: false,
      // 是否显示设备维护弹出层
      devicesOpen: false,
      // 当前操作的收银员
      currentCashier: {},
      // 可选柜组列表
      availableGroups: [],
      // 可选设备列表
      availableDevices: [],
      // 已选择的柜组ID列表
      selectedGroups: [],
      // 已选择的设备ID列表
      selectedDevices: [],
      // 已选择的柜组名称列表
      selectedGroupNames: [],
      // 已选择的设备名称列表
      selectedDeviceNames: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cashierCode: null,
        cashierName: null,
        status: null
      },
      // 表单参数
      form: {},
      // 密码修改表单参数
      passwordForm: {},
      // 表单校验
      rules: {
        cashierCode: [
          { required: true, message: "收银员编码不能为空", trigger: "blur" }
        ],
        cashierName: [
          { required: true, message: "收银员姓名不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: "密码长度必须在6-20位之间", trigger: "blur" }
        ]
      },
      // 密码修改表单校验
      passwordRules: {
        oldPassword: [
          { required: true, message: "原密码不能为空", trigger: "blur" }
        ],
        newPassword: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: "密码长度必须在6-20位之间", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { validator: this.validateConfirmPassword, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询收银员列表 */
    getList() {
      this.loading = true;
      listCashier(this.queryParams).then(response => {
        this.cashierList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消密码修改按钮
    cancelPassword() {
      this.passwordOpen = false;
      this.resetPasswordForm();
    },
    // 表单重置
    reset() {
      this.form = {
        cashierId: null,
        cashierCode: null,
        cashierName: null,
        phone: null,
        password: null,
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    // 密码修改表单重置
    resetPasswordForm() {
      this.passwordForm = {
        cashierCode: null,
        oldPassword: null,
        newPassword: null,
        confirmPassword: null
      };
      this.resetForm("passwordForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.cashierId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加收银员";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const cashierId = row.cashierId || this.ids
      getCashier(cashierId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改收银员";
      });
    },
    /** 修改密码按钮操作 */
    handleChangePassword(row) {
      this.resetPasswordForm();
      this.passwordForm.cashierCode = row.cashierCode;
      this.passwordOpen = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.cashierId != null) {
            updateCashier(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCashier(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交密码修改 */
    submitPasswordForm() {
      this.$refs["passwordForm"].validate(valid => {
        if (valid) {
          changePassword(this.passwordForm).then(response => {
            this.$modal.msgSuccess("密码修改成功");
            this.passwordOpen = false;
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const cashierIds = row.cashierId || this.ids;
      this.$modal.confirm('是否确认删除收银员编号为"' + cashierIds + '"的数据项？').then(function() {
        return delCashier(cashierIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pos/cashier/export', {
        ...this.queryParams
      }, `cashier_${new Date().getTime()}.xlsx`)
    },
    /** 验证确认密码 */
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('确认密码与新密码不一致'));
      } else {
        callback();
      }
    },
    /** 设置柜组按钮操作 */
    handleSetGroups(row) {
      this.currentCashier = row;
      this.loadAvailableGroups();
      this.loadCashierGroups(row.cashierId);
      this.groupsOpen = true;
    },
    /** 设置设备按钮操作 */
    handleSetDevices(row) {
      this.currentCashier = row;
      this.loadAvailableDevices();
      this.loadCashierDevices(row.cashierId);
      this.devicesOpen = true;
    },
    /** 加载可选柜组列表 */
    loadAvailableGroups() {
      listGroup({ status: '0' }).then(response => {
        this.availableGroups = response.rows || [];
      });
    },
    /** 加载可选设备列表 */
    loadAvailableDevices() {
      listDevice({ status: '0' }).then(response => {
        this.availableDevices = response.rows || [];
      });
    },
    /** 加载收银员已关联的柜组 */
    loadCashierGroups(cashierId) {
      getCashierGroups(cashierId).then(response => {
        this.selectedGroups = response.data.map(item => item.groupId);
        this.selectedGroupNames = response.data;
      });
    },
    /** 加载收银员已关联的设备 */
    loadCashierDevices(cashierId) {
      getCashierDevices(cashierId).then(response => {
        this.selectedDevices = response.data.map(item => item.deviceId);
        this.selectedDeviceNames = response.data;
      });
    },
    /** 柜组选择变化 */
    handleGroupChange(value) {
      this.selectedGroupNames = this.availableGroups.filter(group => 
        this.selectedGroups.includes(group.groupId)
      );
    },
    /** 设备选择变化 */
    handleDeviceChange(value) {
      this.selectedDeviceNames = this.availableDevices.filter(device => 
        this.selectedDevices.includes(device.deviceId)
      );
    },
    /** 移除柜组 */
    removeGroup(groupId) {
      this.selectedGroups = this.selectedGroups.filter(id => id !== groupId);
      this.selectedGroupNames = this.selectedGroupNames.filter(group => group.groupId !== groupId);
    },
    /** 移除设备 */
    removeDevice(deviceId) {
      this.selectedDevices = this.selectedDevices.filter(id => id !== deviceId);
      this.selectedDeviceNames = this.selectedDeviceNames.filter(device => device.deviceId !== deviceId);
    },
    /** 提交柜组设置 */
    submitGroups() {
      setCashierGroups(this.currentCashier.cashierId, this.selectedGroups).then(response => {
        this.$modal.msgSuccess("柜组设置成功");
        this.groupsOpen = false;
        this.getList(); // 刷新列表
      });
    },
    /** 提交设备设置 */
    submitDevices() {
      setCashierDevices(this.currentCashier.cashierId, this.selectedDevices).then(response => {
        this.$modal.msgSuccess("设备设置成功");
        this.devicesOpen = false;
        this.getList(); // 刷新列表
      });
    },
    /** 取消柜组设置 */
    cancelGroups() {
      this.groupsOpen = false;
      this.selectedGroups = [];
      this.selectedGroupNames = [];
    },
    /** 取消设备设置 */
    cancelDevices() {
      this.devicesOpen = false;
      this.selectedDevices = [];
      this.selectedDeviceNames = [];
    }
  }
};
</script>

<style scoped>
.dialog-header {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.el-checkbox-group {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.el-tag {
  margin-right: 10px;
  margin-bottom: 5px;
}
</style>
